<template>
  <div class="bg-white rounded-8px">
    <div class=" p-30px flex">
      <div>
        <el-image :src="lessonData.image" fit="cover" style="width: 110px;" />
      </div>
      <div class="ml-20px">
        <div class="text-24px text-dark-500 font-weight-600 mt-10px">{{lessonData.name}}</div>
        <div class="mt-70px">
          <div><el-progress :stroke-width="12" striped :duration="duration" striped-flow :percentage="learnData.percent" /></div>
          <div class="flex justify-between mt-10px text-dark-50">
            <div class="text-14px">总章节：{{ learnData.chapter_count }}节</div>
            <div class="text-14px mr-30px">已学：{{ learnData.learn_count }}节</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="bg-white rounded-8px mt-10px">
    <div class="p-30px">
      <div class="text-20px font-weight-600 text-dark-500 text-center">{{ teachingData.chapter_name }}</div>
      <div class="text-14px font-weight-600 text-dark-100 text-center my-10px">{{ teachingData.section_name }}</div>
      <div class="" ref="contentRef" v-html="resultContent" v-if="type == 1 || type == 2"></div>
      <div class=""  ref="contentRef" v-else>
        <block v-for="(item,index) in teachingData.knowledge">
          <div class="linkText" @click="showKnowledgePopup(item)">{{item.one}}</div>
          <block v-for="(item2,index2) in item.child">
            <div class="ml-10px linkText leading-30px" @click="showKnowledgePopup(item2)">{{item2.two}}</div>
            <block v-for="(item3,index3) in item2.child">
              <div class="ml-40px linkText leading-30px" @click="showKnowledgePopup(item3)">{{item3.three}}</div>
            </block>
          </block>
        </block>
      </div>
      <div class="flex justify-center mt-30px">
        <div class="mx-55px" @click="goPrevSection"><el-button type="danger">上一节</el-button></div>
        <div class="mx-55px" @click="goNextSection"><el-button type="danger">下一节</el-button></div>
      </div>
    </div>
  </div>
  <div class="fixed top-150px right-5px solid">
    <div class="">
      <div class="bg-red-300 linkText text-white rounded-8px p-10px text-center" @click="drawer = true">
        <el-icon :size="20"><Memo /></el-icon>
        <div>目</div>
        <div>录</div>
      </div>
      <div class="bg-red-300 linkText text-white rounded-8px p-10px text-center mt-30px" @click="doSpeak()">
        <el-icon :size="20" v-if="speaking !=1"><Microphone /></el-icon>
        <el-icon :size="20" v-else><Mute /></el-icon>
        <div>音</div>
        <div>频</div>
        <div>阅</div>
        <div>读</div>
      </div>
      <div class="bg-red-300 text-white rounded-8px p-10px text-center mt-30px">
        <div class="linkText" @click="scale += 0.1" :disabled="scale >= 2"><el-icon :size="30"><Plus /></el-icon></div>
        <div class="linkText" @click="scale -= 0.1" :disabled="scale <= 0.5"><el-icon :size="30"><Minus /></el-icon></div>
        <div>字</div>
        <div>体</div>
        <div>调</div>
        <div>节</div>
      </div>
    </div>
  </div>
  <el-drawer v-model="drawer" title="I am the title" :with-header="false">
    <div class="">
      <el-tabs
        v-model="activeName"
        type="card"
        class="demo-tabs justify-between"
       
      >
        <el-tab-pane label="目录" name="first">
          <div class="m-20px mt-0px">
            <block v-for="(item,index) in category" :key="index">
              <div>
                <div class="text-14px text-dark-500 font-500 whitespace-nowrap leading-30px mt-10px">{{item.chapter_name}}</div>
                <block v-for="(itemSon,indexSon) in item.section">
                  <div class="flex linkText" @click="setSection(itemSon.section_id)">
                    <div class="w-4px h-4px bg-red-500 rounded-full self-center mr-5px"></div>
                    <div class="text-12px text-gray-500 leading-25px self-center flex-auto whitespace-nowrap">{{itemSon.section_name}}</div>
                    <div class="self-center">
                      <el-icon><ArrowRight /></el-icon>
                    </div>
                  </div>
                </block>
              </div>
            </block>
          </div>
        </el-tab-pane>
        <el-tab-pane label="重要程度" name="second">
          <div class="m-20px mt-0px">
            <block v-for="(item,index) in categoryByEmphasize" :key="index">
              <div>
                <div class="text-14px text-dark-500 font-500 whitespace-nowrap leading-30px mt-10px">{{item.chapter_name}}、{{item.section_name}}</div>
                <div class="flex linkText" @click="setTeaching(item.teaching_id)">
                  <div class="w-4px h-4px bg-red-500 rounded-full self-center mr-5px"></div>
                  <div class="text-12px text-gray-500 leading-25px self-center flex-auto whitespace-nowrap">{{item.teaching_name}}</div>
                  <div class="self-center">
                    <el-icon><ArrowRight /></el-icon>
                  </div>
                </div>
              </div>
            </block>
          </div>
        </el-tab-pane>
        <el-tab-pane label="薄弱点" name="third">
          <div class="m-20px mt-0">
            <block v-for="(item,index) in categoryByWeaknesses" :key="index">
              <div>
                <div class="text-14px text-dark-500 font-500 whitespace-nowrap leading-30px mt-10px">{{item.chapter_name}}、{{item.section_name}}</div>
                <div class="flex linkText" @click="setTeaching(item.teaching_id)">
                  <div class="w-4px h-4px bg-red-500 rounded-full self-center mr-5px"></div>
                  <div class="text-12px text-gray-500 leading-25px self-center flex-auto whitespace-nowrap">{{item.teaching_name}}</div>
                  <div class="self-center">
                    <el-icon><ArrowRight /></el-icon>
                  </div>
                </div>
              </div>
            </block>

          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-drawer>
  <el-dialog v-model="dialogKnowleageVisible" :title="currentKnowledge.title" width="800">
    <div v-html="currentKnowledge.content"></div>
  </el-dialog>
</template>
<script setup>
import { ref,onMounted,computed,watch, nextTick } from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { systemApi,userApi,httpApi } from '../../api/api'
import { configStore } from '../../stores/config'
import { Minus } from '@element-plus/icons-vue';
import DOMPurify from 'dompurify';
import { ElMessage } from 'element-plus';


const router = useRouter();
const route = useRoute();
const type = ref(route.params.type); // "vue"
const lessonData = ref({});
const teachingData = ref({});
const learnData = ref({});
const scale = ref(1);
const contentRef = ref(null);
const drawer = ref(false)
const activeName = ref('first')
const category = ref([])
const categoryByEmphasize = ref([])
const categoryByWeaknesses = ref([])
const speaking = ref(0)
const currentKnowledge = ref({})
const dialogKnowleageVisible = ref(false)

let synthesis = window.speechSynthesis;
let utterance = null;



const percent = ref(0);
const duration = ref(1000);
const prevSection = ref(0);
const nextSection = ref(0);
const resultContent = ref('');

const config = configStore();

const speak = () => {
  if (synthesis.speaking) synthesis.cancel();
  let content = removeHtmlTags(resultContent.value);
  utterance = new SpeechSynthesisUtterance(content);
  utterance.lang = 'zh-CN';
  synthesis.speak(utterance);
};
const pause = () => synthesis.pause();
const resume = () => synthesis.resume();
const doSpeak = ()=>{
  if(speaking.value == 0){
    console.log("开始")
    speaking.value = 1
    speak()
  }else if(speaking.value == 1){
    speaking.value = 2
    pause()
  }else{
    speaking.value = 1
    resume()
  
  }
}
const showKnowledgePopup=(item)=>{
				currentKnowledge.value = item
				dialogKnowleageVisible.value = true
			}

const removeHtmlTags =(str)=>{
				let tempstr = str.replace(/<[^>]+>/g, '');
				
			  return tempstr.replace(/&nbsp;/g, '');
			}

const init = async ()=>{
      lessonData.value = config.getBook()
      let currentOpen = config.getCurrentOpen() //获取当前阅读章节
      console.log("当前阅读章节：",currentOpen)
      let params = currentOpen
      await getCatalog() //获取目录置前，用于没有teaching_id或者section_id
      
      if(!params.section_id && !params.teaching_id){
        console.log("前置目录数据",category.value)
        params.section_id = category.value[0].section[0].section_id
        
      }
      config.setCurrentOpen(params)
      let res = await httpApi.getTeaching(params)
      
      if(res.code){
        teachingData.value = res.data
        //teachingData.value.teaching_content2 = DOMPurify.sanitize(teachingData.value.teaching_content2)'
        console.log("教材类型：",type);
        if(type.value == 1){
          resultContent.value = DOMPurify.sanitize(teachingData.value.teaching_content2)
        }else{
          resultContent.value = DOMPurify.sanitize(teachingData.value.teaching_content)
        }
        //resultContent.value = DOMPurify.sanitize(teachingData.value.teaching_content2)
        let chapterRes = await httpApi.getChapter({book_id:lessonData.value.book_id})
        if(chapterRes.code){
          learnData.value = chapterRes.data
          duration.value = learnData.value.percent / 25
        }

        computedPrevNext()

      }

      
      await getCatalogByEmphasize()
      getWeakness()
      // console.log("教材内容",res.data)
    }

const getCatalog = async()=>{//获取书本目录章节
				let params = {
					book_id:lessonData.value.book_id
				}
				if(category.value.length == 0){
					let res = await httpApi.getCatalog(params)
					if(res.code){
						category.value = res.data
					}
				}
				
        //console.log("目录",category.value)

				
			}
  const computedPrevNext = ()=>{
      ///获取完目录之后计算上一节跟下一节的ID
				let indexChapter = -1;
				let indexSection = -1;
				if(teachingData.value.chapter_id){
          for (let i = 0; i < category.value.length; i++) {
            console.log(category.value[i].chapter_id,teachingData.value.chapter_id)
              // 检查子数组中是否包含目标元素
              if (category.value[i].chapter_id == teachingData.value.chapter_id) { ///获取本章的索引
                // 如果包含，返回该子数组
              indexChapter = i
              
              //
              for(let j = 0;j<category.value[i].section.length;j++){
                
                if(category.value[i].section[j].section_id == teachingData.value.section_id){
                  indexSection = j
                  //console.log("节索引：",indexSection)
                  //return;
                }
              }
                //return;
              }
          }
        }else{
          indexChapter = 0;
				  indexSection = 0;
        }
				
        console.log(indexChapter,"=====>",indexSection)
        //console.log("目录",indexChapter)

				//先计算上一节
				if(indexSection != 0 ){
					prevSection.value = category.value[indexChapter].section[indexSection-1].section_id
				}else{
					if(indexChapter != 0){
						let lengthSection = category.value[indexChapter-1].section.length
						prevSection.value = category.value[indexChapter-1].section[lengthSection-1].section_id
					}else{
						prevSection.value = 0
					}
				}
				//计算下一节
				if(indexSection != category.value[indexChapter].section.length-1 ){
					nextSection.value = category.value[indexChapter].section[indexSection+1].section_id
				}else{
					if(indexChapter != category.value.length - 1){
						nextSection.value = category.value[indexChapter+1].section[0].section_id
					}else{
						nextSection.value = 0
					}
				}
				 console.log("上一节：",prevSection.value)
				 console.log("下一节",nextSection.value)
				//console.log(this.category)
    
  }

  const getCatalogByEmphasize = async()=>{//获取书本目录章节
    let params = {
      book_id:lessonData.value.book_id
    }
    
    let res = await httpApi.getCatalogByEmphasize(params)
    if(res.code){
      categoryByEmphasize.value = res.data
    }
    
    
    //console.log("重要目录",categoryByEmphasize.value)
  }

  const getWeakness = async()=>{
				let params = {
					book_id:lessonData.value.book_id
				}
				let res = await httpApi.getWeakness(params)
				if(res.code){ //开始处理排序
					let weaknessList = res.data
					// 排序函数
					//console.log("重要程度未排序：",this.categoryByEmphasize)
					let sortTemp = [...categoryByEmphasize.value]
					let sortedArray = sortTemp.sort((a, b) => {
					  // 检查a是否在priorityArray中
					  let indexA = weaknessList.indexOf(a.teaching_id);
					  // 检查b是否在priorityArray中
					  let indexB = weaknessList.indexOf(b.teaching_id);
					
					  // 如果a在priorityArray中，且b不在，那么a应该排在b前面
					  if (indexA !== -1 && indexB === -1) {
					    return -1;
					  }
					  // 如果b在priorityArray中，且a不在，那么a应该排在b后面
					  else if (indexB !== -1 && indexA === -1) {
					    return 1;
					  }
					  // 如果a和b都在priorityArray中，那么根据priorityArray中的顺序来排序
					  else if (indexA !== -1 && indexB !== -1) {
					    return indexA - indexB;
					  }
					  // 如果a和b都不在priorityArray中，那么保持原始顺序（由于使用了稳定排序，所以原始顺序不变）
					  else {
					    return 0;
					  }
					});
					categoryByWeaknesses.value = sortedArray
					// console.log(sortedArray)
					// console.log("重要程度：",this.categoryByEmphasize)
				}
				
			}


const goPrevSection=async()=>{
  console.log(nextSection.value)
  if(prevSection.value == 0){
    ElMessage.error("没有上一节了")
  }
  
  config.setCurrentOpen({section_id:prevSection.value})
  await nextTick()
  setTimeout(()=>{
    init()
    scrollToTop()
  },200)
}
const goNextSection=async()=>{
  console.log(nextSection.value)
  if(nextSection.value == 0){
    ElMessage.error("没有下一节了")
  }
  
  config.setCurrentOpen({section_id:nextSection.value})
  await nextTick()
  // router.push({path:`/book/book/${type.value}`})
  setTimeout(()=>{
    init()
    scrollToTop()
  },200)
}

const setSection = async(section_id)=>{
  config.setCurrentOpen({section_id:section_id})
  await nextTick()
  // router.push({path:`/book/book/${type.value}`})
  setTimeout(()=>{
    init()
    scrollToTop()
    drawer.value = false
  },200)
}

const setTeaching = async(teaching_id)=>{
  config.setCurrentOpen({teaching_id:teaching_id})
  await nextTick()
  // router.push({path:`/book/book/${type.value}`})
  setTimeout(()=>{
    init()
    scrollToTop()
    drawer.value = false
  },200)
}

const scrollToTop = () => {
  // 瞬时滚动到顶部
  window.scrollTo({
    top: 0,
    behavior: "instant", // 或 "smooth"（平滑滚动）
  });

  // 或直接简写
  // document.documentElement.scrollTop = 0;
};

// 遍历所有元素，强制调整字体大小
const applyScaling = () => {
  if (!contentRef.value) return;

  // 遍历容器内的所有元素
  const elements = contentRef.value.querySelectorAll('*');
  elements.forEach(el => {
    const originalSize = parseFloat(el.dataset.originalSize) || parseFloat(getComputedStyle(el).fontSize);
    if (originalSize) {
      el.style.fontSize = `${originalSize * scale.value}px`;
      el.dataset.originalSize = originalSize; // 记录原始大小
    }
  });
};

// 监听缩放比例变化
watch(
  () => route.params.type,
  (newType) => {
    type.value = newType;
    init()
  }
);
// 监听缩放比例变化
watch(scale, () => {
  applyScaling();
});

onMounted(() => {
  init()
  synthesis.cancel()
  const elements = contentRef.value.querySelectorAll('*');
  elements.forEach(el => {
    const fontSize = parseFloat(getComputedStyle(el).fontSize);
    el.dataset.originalSize = fontSize;
  });
  //console.log(type,teaching_id)
})
</script>
<style scoped>
  .linkText{cursor: pointer;}
</style>